package com.imooc.config;

import com.imooc.interceptor.UserTokenInterceptor;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig  implements WebMvcConfigurer {

    // 实现静态资源的映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**") // 映射所有的资源 为指定url请求提供映射服务
                .addResourceLocations("classpath:/META-INF/resources/")  // 映射swagger2 (swagger2也是静态资源文件）
                .addResourceLocations("file:/workspaces/images/");  // 映射本地静态资源 （所要映射的地址）
        //file:/workspaces/images/ 被映射到 localhost:8088/ 地址
        // 也就是说一个请求 localhost:8088/food-dev/xxxx/xxx.png
        // 会被映射到地址 /workspaces/images/food-dev/xxx/xxx.png
    }

    /*
    * 构建一个RestTemplate
    * */
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    /**
     * 创建一个拦截器实例
     * @return 拦截器实例
     */
    @Bean
    public UserTokenInterceptor userTokenInterceptor(){
        return new UserTokenInterceptor();
    }

    /**
     * 添加拦截器
     * @param registry  拦截器的注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * addInterceptor 注册拦截器
         * addPathPatterns 添加拦截器所拦截的请求地址
         * excludePathPatterns 请求不会被拦截
         * /xxx/* 当前xxx路由下的所有子路由
         */
        registry.addInterceptor(userTokenInterceptor())
                .addPathPatterns("/hello")
                .addPathPatterns("/shopcart/add")
                .addPathPatterns("/shopcart/del")
                .addPathPatterns("/address/list")
                .addPathPatterns("/address/add")
                .addPathPatterns("/address/upadte")
                .addPathPatterns("/address/setDefault")
                .addPathPatterns("/address/delete")
                .addPathPatterns("/orders/*")
                .addPathPatterns("/center/*")
                .addPathPatterns("/userInfo/*")
                .addPathPatterns("/myorders/*")
                .addPathPatterns("/mycomments/*")
                .excludePathPatterns("/myorders/deliver")
                .excludePathPatterns("/orders/notifyMerchantOrderPaid");
        // 将注册器添加到 WebMvc的配置类中
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
